<template>
    <div class="debris-detail-box" v-loading="loading">
        <el-form :model="pieceDate" :rules="rules" ref="pieceDate" label-width="120px" class="demo-ruleForm">
            <div class="input-img-box">
                <el-form-item label="图鉴" required>
                    <UploadImg
                        v-model="pieceDate.thumbnail"
                        boxWidth="125"
                        boxHeight="175"
                        width="500"
                        height="700"
                        :search="true"
                    />
                    <el-button type="success" style="margin-top:10px;" v-if="this.pieceDate.banner" @click="copyBanner">使用banner</el-button>
                </el-form-item>

                <el-form-item label="详情banner">
                    <UploadImg
                        v-model="pieceDate.banner"
                        width="1080"
                        height="600"
                        :search="true"
                    />
                </el-form-item>
            </div>
            <el-form-item label="道具" prop="heroName">
                <el-input v-model="pieceDate.heroName" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="道具描述">
                <el-input v-model="pieceDate.name" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="商品状态">
                <el-select v-model="pieceDate.status" placeholder="请选择商品类型">
                    <el-option label="上架" :value="1"></el-option>
                    <el-option label="下架" :value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="关联游戏" prop="gameName">
                <el-select
                    style="width:300px"
                    v-model="pieceDate.gameName"
                    clearable
                    filterable
                    :filter-method="filterGame"
                    :loading="gameLoading"
                    @change="gameSelect"
                    placeholder="请输入并选择关联游戏">
                    <el-option
                        v-for="item in gameList"
                        :key="item.gameid"
                        :label="item.appName"
                        :value="item.gameid">
                            <span style="float: left">
                                <span>{{ item.appName }}</span>
                                <span v-if="item.status === -1" style="color:red;font-size:12px;margin:0 5px;">下架</span>
                            </span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.gameid }}</span>
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="道具类型" prop="categoryName">
                <el-select
                    style="width:300px"
                    v-model="pieceDate.categoryName"
                    clearable
                    filterable
                    @change="categorySelect"
                    placeholder="请输入并选择皮肤类型">
                    <el-option
                        v-for="item in categoryList"
                        :key="item.categoryId"
                        :label="item.categoryName"
                        :value="item.categoryId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="碎片数量" prop="piecePrice" >
                <el-input v-model="pieceDate.piecePrice" style="width:200px"></el-input>
            </el-form-item>

            <el-form-item label="开始时间" prop="validBeginDate">
                <el-date-picker
                    popper-class="channel-picker"
                    :picker-options="pickerOptions"
                    v-model="pieceDate.validBeginDate"
                    type="datetime"
                    @change="timeChange(true)"
                    placeholder="选择开始时间">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="结束时间" prop="validEndDate">
                <el-date-picker
                    popper-class="channel-picker"
                    :picker-options="pickerOptions"
                    v-model="pieceDate.validEndDate"
                    type="datetime"
                    @change="timeChange(false)"
                    placeholder="选择结束时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="详情介绍" prop="notes">
                <el-input type="textarea" v-model="pieceDate.notes" :rows="5"></el-input>
            </el-form-item>

            <el-form-item v-if="toolsFlag > 1">
                <el-button @click="cancle">取消</el-button>
                <el-button type="primary" @click="submitForm('pieceDate')">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { formatDate } from '@/utils/utils'

export default {
    data () {
        const validateBegin = (rule, value, callback) => {
            if (this.pieceDate && this.pieceDate.validEndDate) {
                if (value.getTime() > this.pieceDate.validEndDate.getTime()) {
                    callback(new Error('开始时间不能晚于结束时间'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }

        const validateEnd = (rule, value, callback) => {
            if (this.pieceDate && this.pieceDate.validBeginDate) {
                if (value.getTime() < this.pieceDate.validBeginDate.getTime()) {
                    callback(new Error('结束时间不能早于开始时间'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }

        return {
            loading: false,
            gameLoading: false,
            gameList: [],
            categoryList: [],
            pickerOptions: {
                disabledDate (time) {
                    return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
                },
                selectableRange: '00:00:00 - 23:59:59'
            },
            pieceDate: {
                banner: '',
                categoryName: '',
                gameId: '',
                gameName: '',
                name: '',
                notes: '',
                piecePrice: '',
                skinId: '',
                status: 1,
                thumbnail: ''
            },
            rules: {
                heroName: [
                    { required: true, message: '请输入道具', trigger: 'blur' }
                ],
                gameName: [
                    { required: true, message: '请选择关联游戏', trigger: ['change'] }
                ],
                categoryName: [
                    { required: true, message: '请选择关联游戏类型', trigger: ['change'] }
                ],
                piecePrice: [
                    { required: true, message: '请输入碎片数量', trigger: 'blur' }
                ],
                notes: [
                    { required: true, message: '请输入详情介绍', trigger: 'blur' }
                ],
                validBeginDate: [
                    { required: true, message: '请输入开始时间', trigger: 'blur' },
                    { validator: validateBegin, trigger: 'change' }
                ],
                validEndDate: [
                    { required: true, message: '请输入结束时间', trigger: 'blur' },
                    { validator: validateEnd, trigger: 'change' }
                ]
            },
            toolsFlag: 0 // 是否能保存开关
        }
    },

    watch: {
        pieceDate: {
            handler () {
                this.toolsFlag++
            },
            deep: true
        }
    },
    // computed: {
    //     copyBtnShow () {
    //         return !!this.pieceDate.banner
    //     }
    // },

    mounted () {
        let id = this.$route.query.id
        if (id) {
            this.getDetail(id)
        } else {
            this.dataInit(this.pieceDate)
        }
    },

    methods: {
        // 获取详情
        getDetail (id) {
            this.loading = true
            this.$http.get('/lottrey/selectPieceDetail', { params: { id } }).then(res => {
                this.loading = false
                if (res.code === '0') {
                    this.dataInit(res.data)
                    this.getCategoryList(this.pieceDate.gameId)
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },

        // 初始化数据
        dataInit (data) {
            if (data.validBeginDate) {
                data.validBeginDate = new Date(data.validBeginDate)
            }
            if (data.validEndDate) {
                data.validEndDate = new Date(data.validEndDate)
            }
            // 保存原始数据
            this.firstData = JSON.parse(JSON.stringify(data))
            this.pieceDate = data
            this.toolsFlag = 0
        },

        // 查找游戏
        filterGame (res) {
            clearTimeout(this.timerId)
            if (!res) {
                this.gameLoading = false
                return
            }
            this.gameLoading = true
            this.timerId = setTimeout(() => {
                this.getgameList(res)
            }, 1000)
        },

        async getCategoryList (gameId) { // 获取类型列表
            let params = {
                gameId
            }
            let res = await this.$http.post('/lottrey/selectSkinCategory', params)
            if (res.code === '0') {
                this.categoryList = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
        },

        async getgameList (keyword) { // 获取游戏列表
            let params = {
                keyword,
                pageIndex: 1,
                pageNum: 100
            }
            let res = await this.$http.post('/home/findGames', params)
            if (res.code === '0') {
                this.gameList = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.gameLoading = false
        },
        // 关联游戏
        gameSelect (val) {
            if (!val || this.pieceDate.gameId === val) return
            this.pieceDate.gameId = val
            this.pieceDate.gameName = this.gameList.find(item => {
                return item.gameid === val
            }).appName
            this.pieceDate.categoryName = ''
            this.getCategoryList(val)
        },

        // 更换皮肤类型
        categorySelect (val) {
            if (!val || this.pieceDate.categoryId === val) return
            this.pieceDate.categoryId = val
            this.pieceDate.categoryName = this.categoryList.find(item => {
                return item.categoryId === val
            }).categoryName
        },

        // 校验起止时间
        timeChange (type) {
            if (type && this.pieceDate.validBeginDate) {
                this.$refs.pieceDate.validateField('validEndDate')
            }
            if (!type && this.pieceDate.validEndDate) {
                this.$refs.pieceDate.validateField('validBeginDate')
            }
        },

        // 取消保存
        cancle () {
            this.pieceDate = JSON.parse(JSON.stringify(this.firstData))
            this.toolsFlag = 0
        },
        copyBanner () {
            this.pieceDate.thumbnail = this.pieceDate.banner
        },
        // 保存数据
        submitForm (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let params = Object.assign({}, this.pieceDate)
                    params.validBeginDate = formatDate(params.validBeginDate, 'YYYY-MM-DD HH:MM:SS')
                    params.validEndDate = formatDate(params.validEndDate, 'YYYY-MM-DD HH:MM:SS')
                    if (!params.thumbnail) {
                        return this.$message({
                            type: 'error',
                            message: '请选择图鉴'
                        })
                    }
                    this.$http.post('/lottrey/addPiece', params).then(res => {
                        if (res.code === '0') {
                            this.dataInit(res.data)
                            this.$message({
                                type: 'success',
                                message: '修改成功'
                            })
                            this.$router.go(-1)
                        } else {
                            this.$message({
                                type: 'error',
                                message: res.desc
                            })
                        }
                    })
                } else {
                    return false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    .debris-detail-box {
        max-width: 800px;
        .input-img-box {
            display: flex;
        }
    }
</style>
